import acm.program.ConsoleProgram;


public class CaserCipher extends ConsoleProgram{

	public void run(){
		println("This Program uses a Caesar cipher for encryption.");
		int shift = readInt("Enter encryption key: ");
		String plaintext = readLine("Plaintext: ");
		String ciphertext = encrypt(plaintext,shift);
		println("Ciphertext: "+ ciphertext);
		String plainedtext = decrypt(ciphertext,shift);
		println("plainedText: "+ plainedtext);
	}

	public String encrypt(String plainText, int shift) {
		//TODO Implementieren Sie diese Methode.
		if(shift<0){
			shift= 26-(-shift%26);
		}
		String encryptedText = "";
		for(int i=0; i<plainText.length(); i++){
			char ch = encryptCharacter(plainText.charAt(i),shift);
			encryptedText += ch;
		}
		return encryptedText;
		
		//throw new UnsupportedOperationException("Noch nicht implementiert.");
	}
	
	private char encryptCharacter(char ch, int shift) {
		// TODO Auto-generated method stub
		if(Character.isUpperCase(ch)){
			ch = (char)('A'+(ch-'A'+shift)%26);
			//Character.toUpperCase(ch)
		}		
		else{
			ch = (char)('a'+(ch-'a'+shift)%26);
		}
		return ch;
	}

	public String decrypt(String encryptedText, int shift) {
		//TODO Implementieren Sie diese Methode.
		if(shift>0){
			shift = 26-(shift%26);
		}
		else shift = - shift;
		String plainedText = "";
		for(int i=0; i<encryptedText.length();i++){
			char ch = decryptCharacter(encryptedText.charAt(i),shift);
			plainedText +=ch;
		}
		return plainedText;
		
		//throw new UnsupportedOperationException("Noch nicht implementiert.");
	}

	private char decryptCharacter(char ch, int shift) {
		// TODO Auto-generated method stub
		if(Character.isUpperCase(ch)){
			ch = (char)('A'+(ch-'A'+shift)%26);
		}
		else{
			ch = (char)('a'+(ch-'a'+shift)%26);
		}
		return ch;
	}

}

